package com.jason.core.config.security.service;

import com.jason.core.config.jwt.JwtUser;
import com.jason.core.config.security.MyGrantedAuthority;
import com.jason.entity.SysPermission;
import com.jason.mapper.SysPermissionMapper;
import com.jason.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class JwtUserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    ISysUserService sysUserService;

    @Autowired
    SysPermissionMapper sysPermissionMapper;

    /**
     * 提供一种从用户名可以查到用户并返回的方法
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
/*        *//**TODO:此处需要写明从用户表里面跟根据用户userName查询用户的方法**//*
        JwtUser jwtUser = JwtUserFactory.create(sysUserService.selectUserRole(userName));
        if (jwtUser == null){
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.", userName));
        }
        return jwtUser;*/

        JwtUser jwtUser = sysUserService.selectUserRole(username);
        if (jwtUser != null) {
            List<SysPermission> permissions = sysPermissionMapper.selectPermissionsByUser(jwtUser.getId());
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            for (SysPermission permission : permissions) {
                if (permission != null && permission.getPermissionName()!=null) {

                    GrantedAuthority grantedAuthority = new MyGrantedAuthority(permission.getUrl(), permission.getMethod());
                    //1：此处将权限信息添加到 GrantedAuthority 对象中，在后面进行全权限验证时会使用GrantedAuthority 对象。
                    grantedAuthorities.add(grantedAuthority);
                }
            }
            return new JwtUser(jwtUser.getUsername(), jwtUser.getPassword(), grantedAuthorities);
        } else {
            throw new UsernameNotFoundException("admin: " + username + " do not exist!");
        }
    }
}
